import os
from mysql.connector import pooling
from dotenv import load_dotenv
from hashlib import md5
from dataclasses import dataclass
from typing import Optional
# 加载.env文件
load_dotenv()

host = os.getenv('MYSQL_HOST')
user = os.getenv('MYSQL_USER')
password = os.getenv('MYSQL_PASSWORD')
db = os.getenv('MYSQL_DB')

# 创建一个连接池
dbconfig = {
    "host": host,
    "user": user,
    "password": password,
    "database": db
}
pool = pooling.MySQLConnectionPool(pool_name="my_pool", pool_size=10, **dbconfig)

conn = pool.get_connection()
cursor = conn.cursor()


@dataclass
class AiXinZhiJie:
    title: str
    time: str
    content: str
    create_time: float
    linkMd5: str
    href: Optional[str] = None
    Id: Optional[int] = None


# 获取列表
@staticmethod
def getList():
    sql = "SELECT * FROM aixinzhijie"
    cursor.execute(sql)
    result = cursor.fetchall()
    return result


# 新增
def add(aixinzhijie: AiXinZhiJie):
    sql = "INSERT INTO aixinzhijie(title, `time`, href, linkMd5, content,create_time) VALUES(%s,%s,%s,%s,%s,%s)"
    cursor.execute(sql, (aixinzhijie.title, aixinzhijie.time, aixinzhijie.href, aixinzhijie.linkMd5, aixinzhijie.content, aixinzhijie.create_time))
    conn.commit()

def getLinkMd5(href):
    return md5(href.encode()).hexdigest()

def getListByLinkMd5(linkmd5):
    # linkmd5 = getLinkMd5(href)
    sql = "SELECT * FROM aixinzhijie WHERE linkMd5 = %s"
    cursor.execute(sql, (linkmd5,))
    result = cursor.fetchall()
    return result